package com.xuedongzhilian.service.impl;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.entity.CheckIn;
import com.xuedongzhilian.entity.Rank;
import com.xuedongzhilian.mapper.CheckInMapper;
import com.xuedongzhilian.mapper.RankMapper;
import com.xuedongzhilian.service.IRankingService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 排行榜服务实现类
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Service
public class RankingServiceImpl implements IRankingService {

    @Resource
    private CheckInMapper checkInMapper;
    
    @Resource
    private RankMapper rankMapper;

    @Override
    public Result getCheckInRanking(Integer type, Integer days) {
        // 计算日期范围
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        // 查询指定日期范围内的打卡记录
        List<CheckIn> checkIns = checkInMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CheckIn>()
                .eq("type", type)
                .ge("check_in_date", startDate)
                .le("check_in_date", endDate)
        );
        
        // 统计每个用户的打卡次数
        Map<Long, Long> userCheckInCount = checkIns.stream()
                .collect(Collectors.groupingBy(
                    CheckIn::getUserId,
                    Collectors.counting()
                ));
        
        // 转换为排行榜列表并按打卡次数排序
        List<Map<String, Object>> ranking = userCheckInCount.entrySet().stream()
                .sorted(Map.Entry.<Long, Long>comparingByValue().reversed())
                .map(entry -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("userId", entry.getKey());
                    item.put("checkInCount", entry.getValue());
                    return item;
                })
                .collect(Collectors.toList());
        
        return Result.ok(ranking);
    }

    @Override
    public Result getRankRanking() {
        // 查询段位排行榜，按总分排序
        List<Rank> ranks = rankMapper.selectList(
            new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Rank>()
                .orderByDesc("total_value")
                .last("LIMIT 100") // 限制前100名
        );
        
        return Result.ok(ranks);
    }
}